package com.arch.flink.biz.orderdemo;

import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.builder.Tuple2Builder;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.concurrent.TimeUnit;

/**
 * @author pizhihui
 * @date 2020-12-12
 */
public class ValueStateDemo {


    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        //
        env.enableCheckpointing(60* 1000);
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60*1000);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5, Time.of(10, TimeUnit.SECONDS)));


        Tuple2Builder<Long, Long> tuple2Builder = new Tuple2Builder<>();
        tuple2Builder.add(1L, 5L);
        tuple2Builder.add(2L, 3L);
        tuple2Builder.add(1L, 7L);
        tuple2Builder.add(2L, 5L);
        tuple2Builder.add(1L, 3L);
        tuple2Builder.add(2L, 3L);

        DataStreamSource<Tuple2<Long, Long>> source = env.fromElements(tuple2Builder.build());

        source.keyBy(x -> x.f0)
                .flatMap(new CustomValueState())
                .print();
        env.execute();

    }


    public static class CustomValueState extends RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Double>> {

        private ValueState<Tuple2<Long, Long>> sum;

        @Override
        public void open(Configuration parameters) throws Exception {

            ValueStateDescriptor<Tuple2<Long, Long>> average = new ValueStateDescriptor<>(
                    "average",
                    Types.TUPLE(Types.LONG, Types.LONG));

            sum = getRuntimeContext().getState(average);
        }

        @Override
        public void flatMap(Tuple2<Long, Long> value, Collector<Tuple2<Long, Double>> out) throws Exception {

            Tuple2<Long, Long> currentValue = sum.value();

            if (null == currentValue) {
                currentValue = Tuple2.of(0L, 0L);
            }

            currentValue.f0 += 1;
            currentValue.f1 += value.f1;

            sum.update(currentValue);

            if (currentValue.f0 >= 3) {
                double avg = (double) currentValue.f1 / currentValue.f0;
                out.collect(Tuple2.of(value.f0, avg));
                sum.clear();
            }


        }
    }

}
